#include <qpixmap.h>    //qt中的类
#include <qtimer.h>
#include <QMessageBox>
#include "login.h"
#include "ui_login.h"
#include "mainwindow.h"
#include <QByteArray>
#include <QInputDialog>
#include <qmovie.h>
#include <qdesktopwidget.h>
#include <qpalette.h>
#include "qtq_config.h"
#include "qqdef.hpp"
#include "qqclient.hpp"
#include <stdio.h>
#include <stdlib.h>
#include "debug.hpp"
#include <string.h>
#include <QDebug>
#include "db.h"
extern bool isLoginSuccess;
extern bool isLoginCancel;
//extern int login(uint uid,const char* password,bool ishedden);
extern qqclient* qq;

extern MainWindow* wMain;
extern Login* wLogin;
extern bool soundState;
int login(uint uid,const char* password,bool ishedden)
{
    DBG( "qqclient_create()" );
    qqclient_create( qq, uid, (char*)password );
    qq->mode = ishedden ? QQ_HIDDEN : QQ_ONLINE;
    DBG( "qqclient_login()" );
    qqclient_login( qq );
    DBG( "login() end" );
}
Login::Login(QWidget *parent) :
    QDialog(parent),status(0),sound(1),
    ui(new Ui::Login)
{

    ui->setupUi(this);
    ui->lblVerycode->setText("");
    QDesktopWidget* desktop = QApplication::desktop(); // =qApp->desktop();也可以
    move((desktop->width() - this->width())/2, (desktop->height() - this->height())/2);

    //ui->txtUser->setText("21552550");
    //ui->txtPass->setText("qq21552550");
    db &infoDB = db::GetInstance();
    infoDB.open(0);
    infoDB.readAccount( this->accountList );
    QString account;
    if(this->accountList.size()>0)
    {
        account = accountList[0];
        for(int i =0; i < accountList.size();i++)
        {
            QString tmpAccount = accountList[i];
            QStringList tmpAcountlist = tmpAccount.split("\t",QString::SkipEmptyParts);
            if(tmpAcountlist.size()>1)
            {
                this->ui->lstAccount->addItem(tmpAcountlist[0]);
            }
        }
    }

    QStringList acountlist = account.split("\t",QString::SkipEmptyParts);
    QString uid = "";
    QString pwd = "";
    if(acountlist.size()>1)
    {
        uid = acountlist[0];
        pwd = acountlist[1];
    }
    else
    {
        uid = account;
    }
    if(uid.size()>0)
    {
        ui->txtUser->setText(uid);
        ui->txtPass->setText(pwd);
    }

    ui->txtUser->setFocus();
    ui->progressBar->setVisible(false);

    ui->btnCancel->setVisible(false);

    lblBG = new QClickedLabel(this);
    lblBG->setPixmap(QPixmap(RC_PREFIX "QQTheme/BK.PNG")) ;
    lblBG->setGeometry(0,0, this->width(),this->height() );
    lblBG->lower();
//    lblBG->setFixedWidth( this->width() );
//    lblBG->setFixedHeight( this->height() );
    this->ui->lstAccount->setVisible(false);


    this->ui->btnSelectAccount->setFlat(true);
    this->ui->btnSelectAccount->setText("");
    //this->ui->btnSelectAccount->resize(20,16);
    this->ui->btnSelectAccount->setIconSize(QSize(20,16));


    this->ui->btnSelectAccount->setIcon(QPixmap(RC_PREFIX "QQTheme/PowerTreeFlag2.png"));
    connect( this->ui->btnSelectAccount, SIGNAL(clicked()),SLOT(SelectAccountClick()));
    connect( this->ui->lstAccount, SIGNAL(currentRowChanged(int)),this,SLOT(OnSelectAccount(int)));

    lblLoading = new QClickedLabel(this);
    lblLoading->setPixmap(QPixmap(RC_PREFIX "QQTheme/LOGINING.GIF"));
    lblLoading->setGeometry(0,0, this->width(),this->height() );
    lblLoading->setVisible(false);
    lblLoading->lower();


//    ui->btnLogin->setFlat(true);
//    ui->btnCancel->setFlat(true);
    connect(ui->btnLogin, SIGNAL(clicked()),SLOT(loginClick()));
    connect(ui->btnExit,SIGNAL(clicked()),SLOT(exitClick()));
    connect(ui->btnCancel,SIGNAL(clicked()),SLOT(cancelClick()));

    timer = new QTimer(this);
    connect( timer, SIGNAL(timeout()), this, SLOT(timerDone()) );
    connect( this, SIGNAL(cancelLogin()),timer, SLOT(stop()) );

    lblNextStatus = new QClickedLabel(this);
    lblNextStatus->setGeometry(300,420, 16,20 );
    lblNextStatus->setPixmap(QPixmap(RC_PREFIX "QQTheme/PowerTreeFlag1"));
    connect( lblNextStatus, SIGNAL(Clicked(QClickedLabel*)),this, SLOT(lblNextStatusClicked(QClickedLabel*)) );

    lblStatus = new QClickedLabel(this);
    lblStatus->setGeometry(100,420, 100,20);
    lblStatus->setText(QObject::tr("在线"));


    lblNextSetting = new QClickedLabel(this);
    lblNextSetting->setGeometry(300,470, 56,20 );
    lblNextSetting->setPixmap(QPixmap(RC_PREFIX "QQTheme/PowerTreeFlag1"));
    connect( lblNextSetting, SIGNAL(Clicked(QClickedLabel*)),this, SLOT(lblNextSettingClicked(QClickedLabel*)) );

    lblSetting = new QClickedLabel(this);
    lblSetting->setGeometry(100,470, 100,20);
    lblSetting->setText(QObject::tr("有声模式"));

    QPalette pal(QColor(255,255,255));
    pal.setColor( QPalette::Text, QColor(255,255,255) );
    pal.setColor( QPalette::Foreground, QColor(255,255,255) );

    lblStatus->setPalette(pal);
    lblSetting->setPalette(pal);



}
void Login::onDisplayVerCode(QString &vFile)
{
    QPixmap vPixmap = QPixmap(vFile);
    this->ui->lblVerycode->setPixmap( vPixmap );
    this->ui->lblVerycode->resize(vPixmap.width(), vPixmap.height());
}

void Login::displayVerycode()
{
    char path[PATH_LEN];
    sprintf( path, "%s/%u.png", qq->verify_dir, qq->number );
    QPixmap vPixmap = QPixmap(path);
    ui->lblVerycode->setPixmap(vPixmap) ;
    lblBG->setGeometry((this->width() - vPixmap.width())/2,
                       0,
                       vPixmap.width(),
                       vPixmap.height() );
}

void Login::lblNextStatusClicked(QClickedLabel* label)
{
    //static int status = 0;
    if(status == 0)
    {
        lblStatus->setText(QObject::tr("隐身"));
        status = 1;
    }
    else
    {
        lblStatus->setText(QObject::tr("在线"));
        status = 0;
    }
}

void Login::lblNextSettingClicked(QClickedLabel* label)
{
    //static int Setting = 0;
    if(sound == 0)
    {
        lblSetting->setText(QObject::tr("有声模式"));
        sound = 1;
    }
    else
    {
        lblSetting->setText(QObject::tr("安静模式"));
        sound = 0;
    }
    soundState = sound == 1;
}

Login::~Login()
{
    delete ui;
}

void Login::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
void Login::SelectAccountClick()
{
    this->ui->lstAccount->setVisible( !this->ui->lstAccount->isVisible() );
}

void Login::loginClick()
{
    showStage(1);
    QApplication::processEvents();
    int uid = this->ui->txtUser->text().toInt();
    QByteArray bpass = this->ui->txtPass->text().toLatin1();
    const char* spass = bpass.data();
    login(uid,spass,status == 1 ? true : false);
}

void Login::OnSelectAccount(int currentRow)
{
    QString account;
    if(this->accountList.size()>0)
    account = accountList[currentRow];

    QStringList acountlist = account.split("\t",QString::SkipEmptyParts);
    QString uid = "";
    QString pwd = "";
    if(acountlist.size()>1)
    {
        uid = acountlist[0];
        pwd = acountlist[1];
    }
    else
    {
        uid = account;
    }
    if(uid.size()>0)
    {
        ui->txtUser->setText(uid);
        ui->txtPass->setText(pwd);
    }
    this->ui->lstAccount->setVisible(false);
}

void Login::showStage(int index)
{
    switch(index) // 0 login,1 logining,2 main
    {
    case 0:
        this->ui->txtPass->setVisible(true);
        this->ui->txtUser->setVisible(true);
        this->ui->btnLogin->setVisible(true);
        this->ui->btnCancel->setVisible(true);
        this->ui->progressBar->setVisible(false);
        this->ui->btnCancel->setVisible(false);
        this->ui->btnExit->setVisible(true);
        this->ui->btnSelectAccount->setVisible(true);

        lblLoading->setVisible(false);
        this->lblBG->setVisible(true);
        this->lblNextSetting->setVisible(true);
        this->lblSetting->setVisible(true);
        this->lblStatus->setVisible(true);
        this->lblNextStatus->setVisible(true);

        timer->stop();
        break;
    case 1:
        this->ui->btnSelectAccount->setVisible(false);
        this->ui->txtPass->setVisible(false);
        this->ui->txtUser->setVisible(false);
        this->ui->btnLogin->setVisible(false);
        this->ui->btnCancel->setVisible(true);
        this->ui->progressBar->setVisible(true);
        this->ui->btnExit->setVisible(false);
        this->lblBG->setVisible(false);
        lblLoading->setVisible(true);
        this->lblNextSetting->setVisible(false);
        this->lblSetting->setVisible(false);
        this->lblStatus->setVisible(false);
        this->lblNextStatus->setVisible(false);

        timer->start(500); // 2秒单触发定时器
        break;
    case 2:
        break;
    }
}

void Login::timerDone()
{
#ifdef WINSCW
    timer->stop();
    emit LoginSuccess();
    this->close();
#endif

    int v = this->ui->progressBar->value() + 10;
    if(v < 100)
    {
        ui->progressBar->setValue( v);
    }
    else
    {
        ui->progressBar->setValue(0);
    }
    isLoginSuccess = false;
    isLoginCancel = false;
    if( qq->process == P_LOGGING )
            return;
    if( qq->process == P_VERIFYING ){
        QString vfilepath = QString("%1/%2.png").arg(qq->verify_dir).arg(qq->number);
        wLogin->onDisplayVerCode(vfilepath);
        bool ok;
        this->timer->stop();
        QString sInput = QInputDialog::getText(0, "info",QObject::tr("请输入验证码:"),QLineEdit::Normal,"",&ok);
        if ( ok && !sInput.isEmpty() ) {
            QByteArray ba = sInput.toLatin1();
            char* input = ba.data();
            DBG("very code:%s",input);
            qqclient_verify( qq, *(uint*)input );
            //qqclient_wait( qq, 3 ); /*wait one second*/
            while( qq->process == P_LOGGING )
            {
                QApplication::processEvents();
                qqclient_wait( qq, 1 );
            }

            this->timer->start();
            return;
        }
        else
        {
            isLoginCancel = true;
        }
    }
    if( qq->process != P_LOGIN ){
            isLoginCancel = true;
            switch( qq->process ){
            case P_ERROR:
                    QMessageBox::critical(0,"critical",QObject::tr("网络错误."));

                    break;
            case P_DENIED:
                    QMessageBox::critical(0,"critical",QObject::tr("您的QQ需要激活(http://jihuo.qq.com)."));
#ifdef __WIN32__
                    ShellExecute(NULL,L"open",L"http://jihuo.qq.com/",NULL,NULL,SW_SHOWNORMAL);
#endif

                    break;
            case P_WRONGPASS:
                    QMessageBox::critical(0,"critical",QObject::tr("您的密码错误."));

                    break;
            }

    }
    else
    {
        isLoginSuccess = true;
        if(!qq->login_finish)
        {
            return;
        }
    }
    if(isLoginCancel)
    {
        showStage(0);
        QApplication::processEvents();
        qqclient_logout( qq );
        qqclient_cleanup( qq );

    }//判断是否登陆成功
    else if(isLoginSuccess)
    {
//        MainWindow w;
//#ifdef __SYMBIAN32__
//        w.showFullScreen();
//#else
//        w.show();
//#endif
        //save qq number;
        db &infoDB = db::GetInstance();
        infoDB.open(0);
        QString uid = QString("%1").arg(qq->number);
        QString pass = this->ui->txtPass->text();
        infoDB.writeAccount(uid,pass);

        infoDB.open(qq->number);
        



        timer->stop();
        emit LoginSuccess();
        this->close();
    }
}

void Login::cancelClick()
{
    emit cancelLogin();
    showStage(0);
}

void Login::exitClick()
{
    //QApplication::exit();
    this->close();
    wMain->close();
}
//void Login::createActions()
//{
//    actHidden = new QAction(tr("&Hidden"), this);
//    actHidden->setIcon();
//}
